
package moa.sequencestreams.generator;

import java.lang.String;

import org.apache.commons.math.random.RandomDataImpl;

public class Transaction {
	private	  int tlen;	// expected number of items in transaction
	private	  int nitems;	// number of items currently in transaction
	private int maxsize;	// size of array items
	private int[] items;	// items in the transaction

	private static int cid_len = 10;   // ASCII field-width of customer-id
	private  static int tid_len = 10;   // ASCII field-width of transaction-id
	private  static int item_len = 10;  // ASCII field-width of item-id

	private  static int tid = 0;	// transaction-id


	public Transaction(int sz)
	{
		tlen=sz;
		nitems=0;
		maxsize=5 * sz;
	  // maximum size of a transaction is 5 * sz
	  items = new int [maxsize];
	}
	
	public void sort()
	{
	  int val;
	  int i, j;

	  for (i = 1; i < nitems; i++ )
	    {
	      val = items[i];
	      for ( j = i; j > 0 && items[j-1] > val; j-- )
			items[j] = items[j-1];

	      items[j] = val;
	    }
	}


	public boolean add_item(int itm)
	{ 
	  int i;
	  for (i = 0; i < nitems; i++)
	    if ( items[i] == itm )
	    {
			//System.out.println("Add an item false");
	    	return false;
	    }

	  if (nitems >= maxsize) {	// allocate more memory
	    int[] old_items = items;
	    maxsize *= 2;
	    items = new int [maxsize];
	    for (i = 0; i < nitems; i++)
	      items[i] = old_items[i];
	    //delete [] old_items;
	  }
	  items[nitems] = itm;
	  //System.out.println("Item added successfully dams items [" + nitems + "]  = "+ itm );
	  nitems ++;
	  return true;
	}


	// adds pattern to transaction
	// returns TRUE if pattern was added, FALSE else
	//
	public boolean add(ArrayString pat, boolean corrupt)
	{
		RandomDataImpl rd = new RandomDataImpl();
	  int i, patlen;
	  
	  // corrupt the pattern by reducing its length;
	  // conf_lvl for a pattern is decided at the time of pattern creation
	  patlen = pat.size();
	  if ( corrupt )
	    while ( patlen > 0 && rd.nextUniform(0, 1) > pat.conf_lvl() )
	      patlen--;
	  
	  // in half of the cases, we drop the pattern that won't fit
	  if ( patlen+nitems > tlen )	// not enough space left
	    if ( rd.nextUniform(0, 1) > 0.5 )
	    {
		      return false;
	    }

	  
	  // pick "patlen" items at random from pattern
	  Choose shuffle = new Choose (pat.size(), patlen);
	  for (i = 0; i < patlen; i++)
	  {
		  add_item( pat.item(shuffle.pos(i)) ); // allocates extra space if necessary
		  //System.out.println ("Itm = " + pat.item(shuffle.pos(i)));
	  }

	  
	  return true;
	}
	
	public String write(int cid)
	{
		String seq = "";
		  if ( nitems == 0 )
			    return null;
			  sort();

			  tid++;
			  if (cid == 0)		// no customer-id; set cust-id to trans-id
			    cid = tid;

			  for (int i = 0; i < nitems; i++) {
				 seq = seq +  items[i] + " " ;
			    //System.out.print (items[i] + " ");
			  }
		return seq;
	}
	
	public int size() { return nitems; }

}
